package userlogic

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	logic "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/redis_utils"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"github.com/zeromicro/go-zero/core/logx"
)

type OfflineLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOfflineLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OfflineLogic {
	return &OfflineLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OfflineLogic) Offline(in *login_rpc.OfflineReq) (resp *login_rpc.OfflineResp, err error) {
	if in.IsAdmin {
		err = l.offlineAdmin(in.UserIds)
	} else {
		err = l.offlineNormalUsers(in.UserIds)
	}

	if err != nil {
		resp.CommonResp.Code = config.DBError
		resp.CommonResp.Message = err.Error()
	}

	return
}

func (l *OfflineLogic) offlineAdmin(userIds []int64) error {
	if len(userIds) == 0 {
		return nil
	}

	db := l.svcCtx.Db.Begin()
	if err := model.NewAdminUserModel(l.ctx, db).Logout(userIds...); err != nil {
		db.Rollback()
		return err
	}

	tokens := model.NewAdminLoginToken(l.ctx, db).List(userIds...)
	if err := model.NewAdminLoginToken(l.ctx, db).CleanAllLoginTokenOfUser(userIds...); err != nil {
		db.Rollback()
		return err
	}

	db.Commit()

	keys := make([]string, 0, len(userIds))
	for _, token := range tokens {
		keys = append(keys, logic.BuildRedisKey(l.ctx, token.UserId, true, token.Business, token.Source))
	}

	redisCli := logic.GetRedisClient(l.svcCtx.Config.RedisConfig)
	_, err := redisCli.Del(l.ctx, keys...).Result()
	if err != nil {
		logc.Errorf(l.ctx, "clean admin token from redis err: %v", err)
	}

	return nil
}

func (l *OfflineLogic) offlineNormalUsers(userIds []int64) error {
	if len(userIds) == 0 {
		return nil
	}

	db := l.svcCtx.Db.Begin()
	if err := model.NewUserModel(l.ctx, db).Logout(userIds...); err != nil {
		db.Rollback()
		return err
	}

	tokens := model.NewUserLoginTokenModel(l.ctx, db).List(userIds...)
	if err := model.NewUserLoginTokenModel(l.ctx, db).CleanAllLoginTokenOfUser(userIds...); err != nil {
		db.Rollback()
		return err
	}

	db.Commit()

	keys := make([]string, 0, len(userIds))
	for _, token := range tokens {
		keys = append(keys, logic.BuildRedisKey(l.ctx, token.UserId, false, token.Business, token.Source))
	}

	redisCli := logic.GetRedisClient(l.svcCtx.Config.RedisConfig)
	_, err := redisCli.Del(l.ctx, keys...).Result()
	if err != nil {
		logc.Errorf(l.ctx, "clean user token from redis err: %v", err)
	}

	return nil
}
